package gateway.core;

import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class HeartbeatProvider {

    private String mgtAddress;
    private String coreName;
    private String serviceId;

    private CredentialsProvider provider = new BasicCredentialsProvider();

    private long interval = 1000 * 60;
    private String registered = "false";

    public HeartbeatProvider(String mgtAddr, String username, String password, String coreName, String serviceId) {
        this.mgtAddress = mgtAddr;
        this.coreName = coreName;
        this.serviceId = serviceId;

        this.provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        new Thread(() -> {
            while (true) {
                this.beat();

                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Heartbeat-Provider").start();
    }

    private void beat() {
        try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build()) {
            HttpPost httpPost = new HttpPost(mgtAddress + "/gatewayCore/refresh");

            List<NameValuePair> form = new LinkedList<>();
            form.add(new BasicNameValuePair("coreName", coreName));
            form.add(new BasicNameValuePair("serviceId", serviceId));
            form.add(new BasicNameValuePair("registered", registered));
            form.add(new BasicNameValuePair("dateSent", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date())));

            httpPost.setEntity(new UrlEncodedFormEntity(form, Consts.UTF_8));

            String responseBody = httpClient.execute(httpPost, (HttpResponse response) -> EntityUtils.toString(response.getEntity()));

            if ("success".equals(responseBody)) {
                registered = "true";
            } else {
                registered = "false";
            }
        } catch (Exception ex) {
            System.err.println("Registration failed, " + ex.getMessage());
        }
    }
}
